/**
 *@description:TODO
 * @author: cai
 *@time:2017年10月13日上午11:54:46
 */
package com.pos.modules.cashier;

import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.pos.BaseActivity;
import com.pos.R;
import com.pos.modules.ScannerActivity;
import com.pos.modules.bean.UserBean;
import com.pos.modules.cashier.adapter.GoodsListAdapter;
import com.pos.modules.cashier.adapter.GoodsListAdapter.DoAction;
import com.pos.modules.cashier.bean.GoodsBean;
import com.pos.net.base.Request.Method;
import com.pos.net.netparam.NetParams;
import com.pos.net.netparam.RequestUrls;
import com.pos.net.request.interfa.BaseRequestListener;
import com.pos.net.request.interfa.JsonRequestListener;
import com.pos.set.AppSet;
import com.pos.set.db.HangGoodsProvider;
import com.pos.set.db.HangGoodsProvider.GoodsConstants;
import com.pos.toolbox.FinancialUtils;
import com.pos.toolbox.file.FilesManager;
import com.pos.widgets.ScanGunKeyEventHelper;
import com.pos.widgets.dialog.CommonDialog;
import com.pos.widgets.swipe.CustomSwipeListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:收银台主页
 * @author cai
 * @time:2017年10月13日上午11:54:46
 */
public class CashierActivity extends BaseActivity
		implements OnClickListener, ScanGunKeyEventHelper.OnScanSuccessListener {
	private String goodsCode;
	private List<GoodsBean> goodsList;
	private GoodsListAdapter adapter;
	private CustomSwipeListView swipeListView;
	private TextView text_total, text_submit;
	private EditText edit_code;
	private ImageView image_delete;
	private RelativeLayout relative_submit;
	private Button button_clear, button_hang, button_input, button_member;
	private long totalFen = 0;
	private UserBean userBean;
	private ContentResolver mContentResolver;
	private Gson gson;
	private LinearLayout linear_input;
	private CommonDialog commonDialog;
	private ScanGunKeyEventHelper mScanGunKeyEventHelper;
	private EditText edit_member;
	private TextView text_member_hint, text_member_search, text_member_name, text_member_level, text_member_credits,
			text_member_amount;
	private Button button_member_confirm, button_member_clear;
	private Dialog memberDialog;
	private View memberView;
	private LayoutInflater inflater;
	private String memberCode, memberName, levelName, memberScore, memberBalance, memberPayToken = "";
	private TextView text_common_title, text_common_right;
	private LinearLayout linear_title_back;
	private ImageView image_common_title_function;

	@Override
	public void initView() {
		setContentView(R.layout.cashier_layout);
		swipeListView = bindId(R.id.swipeListView);
		text_total = bindId(R.id.text_total);
		edit_code = bindId(R.id.edit_code);
		// text_search = bindId(R.id.text_search);
		image_delete = bindId(R.id.image_delete);
		text_submit = bindId(R.id.text_submit);
		relative_submit = bindId(R.id.relative_submit);
		button_clear = bindId(R.id.button_clear);
		button_hang = bindId(R.id.button_hang);
		button_input = bindId(R.id.button_input);
		button_member = bindId(R.id.button_member);
		linear_input = bindId(R.id.linear_input);

		memberDialog = new Dialog(mContext, R.style.dialog);
		inflater = LayoutInflater.from(mContext);
		memberView = inflater.inflate(R.layout.dialog_member_layout, null);
		edit_member = bindId(memberView, R.id.edit_member);
		text_member_hint = bindId(memberView, R.id.text_member_hint);
		text_member_search = bindId(memberView, R.id.text_member_search);
		text_member_name = bindId(memberView, R.id.text_member_name);
		text_member_level = bindId(memberView, R.id.text_member_level);
		text_member_credits = bindId(memberView, R.id.text_member_credits);
		text_member_amount = bindId(memberView, R.id.text_member_amount);
		button_member_confirm = bindId(memberView, R.id.button_member_confirm);
		button_member_clear = bindId(memberView, R.id.button_member_clear);
		text_common_title = bindId(R.id.text_common_title);
		linear_title_back = bindId(R.id.linear_title_back);
		text_common_right = bindId(R.id.text_common_right);
		image_common_title_function = bindId(R.id.image_common_title_function);
		memberDialog.setContentView(memberView);
		Window dialogWindow = memberDialog.getWindow();
		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
		WindowManager.LayoutParams p = dialogWindow.getAttributes();
		// p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6
		p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65
		dialogWindow.setAttributes(p);
		memberDialog.setCancelable(false);
	}

	@Override
	public void initData() {
		commonDialog = new CommonDialog(mContext);
		AppSet.cashierActivities.add(this);
		mScanGunKeyEventHelper = new ScanGunKeyEventHelper(this);
		registerBoradcastReceiver();
		userBean = (UserBean) FilesManager.readObject(mContext, FilesManager.User);
		mContentResolver = getContentResolver();
		gson = new Gson();
		text_common_title.setText("收银台");
		linear_title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				commonDialog.showDialog("确定退出收银台？", "确定", new OnClickListener() {

					@Override
					public void onClick(View v) {
						commonDialog.dismissDialog();
						finish();

					}
				});

			}
		});
		text_common_right.setVisibility(View.GONE);
		image_common_title_function.setVisibility(View.VISIBLE);
		image_common_title_function.setImageResource(R.drawable.image_scanner);
		image_common_title_function.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(mContext, ScannerActivity.class), 0);

			}
		});

		// ActionBarManager.init(this, "收银台", true, R.drawable.image_scanner,
		// new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// startActivityForResult(new Intent(mContext, ScannerActivity.class),
		// 0);
		//
		// }
		// });
		Log.e(Tag, "第一次进入");
		goodsList = (ArrayList<GoodsBean>) getIntent().getSerializableExtra("goodsList");
		if (goodsList == null) {
			goodsList = new ArrayList<>();
		}
		adapter = new GoodsListAdapter(mContext, goodsList, new DoAction() {

			@Override
			public void onMinus(int position) {
				if (goodsList.get(position).getNum() > 1) {
					goodsList.get(position).setNum(goodsList.get(position).getNum() - 1);
					adapter.notifyDataSetChanged();
					dealAccount();
				}

			}

			@Override
			public void onDelete(int position) {
				goodsList.remove(position);
				adapter.notifyDataSetChanged();
				dealAccount();
			}

			@Override
			public void onAdd(int position) {
				goodsList.get(position).setNum(goodsList.get(position).getNum() + 1);
				adapter.notifyDataSetChanged();
				dealAccount();
			}
		});
		swipeListView.setAdapter(adapter);
		dealAccount();
//		edit_code.setFocusable(true);
//		edit_code.setFocusableInTouchMode(true);
//		edit_code.requestFocus();
//		edit_code.setVisibility(View.GONE);
	}

	@Override
	public void initListener() {
		edit_member.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!TextUtils.isEmpty(s.toString())) {
					text_member_hint.setVisibility(View.GONE);
				}

			}
		});
		edit_code.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					switch (event.getAction()) {
						case KeyEvent.ACTION_UP:
							goodsCode = edit_code.getText().toString();
							if (TextUtils.isEmpty(goodsCode)) {
								showShortToast("请输入商品码");
								return false;
							}

							Log.e("onEditorAction", "onEditorAction*******goodsCode=" + goodsCode + "******");
							InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(edit_code.getWindowToken(), 0);
							netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posQueryGoodsByCode, Method.POST,
									NetParams.posQueryGoodsByCode(mContext, goodsCode), 0, listener);
							return true;

						default:
							return true;
					}

				}
				return false;
			}
		});
		image_delete.setOnClickListener(this);
		// text_search.setOnClickListener(this);
		text_submit.setOnClickListener(this);
		button_clear.setOnClickListener(this);
		button_hang.setOnClickListener(this);
		button_input.setOnClickListener(this);
		button_member.setOnClickListener(this);
		text_member_search.setOnClickListener(this);
		button_member_confirm.setOnClickListener(this);
		button_member_clear.setOnClickListener(this);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
			goodsCode = data.getStringExtra("goodsCode");
				Log.e("goodsCode", "goodsCode=" + goodsCode);
				netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posQueryGoodsByCode, Method.POST,
						NetParams.posQueryGoodsByCode(mContext, goodsCode), 0, listener);
			} else if (requestCode == 1) {
				goodsList.clear();
				adapter.notifyDataSetChanged();
				memberCode = "";
				memberPayToken = "";
				memberName = "";
				levelName = "";
				memberScore = "";
				memberBalance = "";
				memberPayToken = "";
				edit_code.setText("");
				edit_member.setText("");
				text_member_amount.setText("");
				text_member_credits.setText("");
				text_member_level.setText("");
				text_member_name.setText("");
				dealAccount();
			}

		}
	}

	/**
	 * 截获按键事件.发给ScanGunKeyEventHelper
	 *
	 * @param event
	 * @return
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (mScanGunKeyEventHelper.isScanGunEvent(event)) {
			mScanGunKeyEventHelper.analysisKeyEvent(event);
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onResume() {
		super.onResume();

		Log.e(Tag, "CashierActivity    onResume********");
		if (!mScanGunKeyEventHelper.hasScanGun()) {
			// Toast.makeText(mContext, "未检测到扫码枪设备", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(stateChangeReceiver);
		mScanGunKeyEventHelper.onDestroy();
	}

	@Override
	public void onScanSuccess(String barcode) {
		Log.e(Tag, "onScanSuccess barcode=" + barcode);
		System.out.println("************barcode=" + barcode);
		goodsCode = barcode;
	//	edit_code.setText(goodsCode);
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edit_code.getWindowToken(), 0);
		netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posQueryGoodsByCode, Method.POST,
				NetParams.posQueryGoodsByCode(mContext, goodsCode), 0, listener);
	}

	private void registerBoradcastReceiver() {
		IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
		IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
		registerReceiver(stateChangeReceiver, filter1);
		registerReceiver(stateChangeReceiver, filter2);
	}

	private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
				// Toast.makeText(mContext, "蓝牙设备连接状态已变更",
				// Toast.LENGTH_SHORT).show();
			} else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
				// Toast.makeText(mContext, "蓝牙设备连接状态已变更",
				// Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	private void dealAccount() {
		if (goodsList.size() == 0) {
			relative_submit.setVisibility(View.GONE);
		} else {
			relative_submit.setVisibility(View.VISIBLE);
			totalFen = 0;
			for (GoodsBean item : goodsList) {
				totalFen = totalFen + item.getPrice() * item.getNum();
			}
			text_total.setText("¥" + FinancialUtils.fen2yuan(totalFen));
		}

	}

	private BaseRequestListener listener = new JsonRequestListener() {

		@Override
		public void onStart(int requestId) {
			if (requestId == 2) {
				text_member_hint.setVisibility(View.VISIBLE);
				text_member_hint.setText("正在查询会员信息...");
			} else {
				showDialg();
			}
		}

		@Override
		public void onError(int requestId, int errorCode, String errorMsg) {
			disMissDialog();
			if (requestId == 2) {
				memberDialog.dismiss();
				dealError(errorCode, errorMsg);
			} else {
				dealError(errorCode, errorMsg);
				edit_code.setText("");
			}

		}

		@Override
		public void onSuccess(int requestId, String url, JSONObject jsonResult) {
			Log.e("TAG", "onSuccess22222222: "+jsonResult.toString() );
			disMissDialog();
			if (requestId == 0) {
				edit_code.setText("");
				int retCode = jsonResult.optInt("retCode", 0);
				if (retCode == 1) {
					showShortToast("商品不存在");
					return;
				}
				if (retCode == 2) {
					showShortToast("商品库存不足");
					return;
				}
				GoodsBean goodBean = new GoodsBean(goodsCode, jsonResult.optString("goodsName"),
						jsonResult.optLong("goodsPrice", 0), 1);
				goodsList.add(goodBean);
				adapter.notifyDataSetChanged();
				dealAccount();
			} else if (requestId == 1) {
				int retCode = jsonResult.optInt("retCode", 0);
				if (retCode == 1) {
					showShortToast("创建订单失败");
					return;
				}
				if (retCode == 2) {
					showShortToast("商品库存不足：" + jsonResult.optString("addtional"));
					return;
				}
				JSONArray goods = jsonResult.optJSONArray("goods");
				Intent intent = new Intent(mContext, AccountActivity.class);
				intent.putExtra("orderId", jsonResult.optString("orderId"));
				intent.putExtra("goods", goods.toString());
				intent.putExtra("memberBalance", memberBalance);
				intent.putExtra("memberCode", memberCode);
				intent.putExtra("memberPayToken", memberPayToken);
				intent.putExtra("levelName", levelName);
				intent.putExtra("memberScore", memberScore);
				intent.putExtra("totalPrice", jsonResult.optLong("totalPrice", 0));
				intent.putExtra("finalPrice", jsonResult.optLong("finalPrice", 0));
				intent.putExtra("discountPrice", jsonResult.optLong("discountPrice", 0));
				intent.putExtra("orderCode", jsonResult.optString("orderCode"));
				// startActivity(intent);
				startActivityForResult(intent, 1);
			} else if (requestId == 2) {
				text_member_hint.setVisibility(View.GONE);
				int retCode = jsonResult.optInt("retCode", 0);
				if (retCode == 1) {
					text_member_hint.setText("查询会员信息失败");
					text_member_hint.setVisibility(View.VISIBLE);
					return;
				}
				memberName = jsonResult.optString("memberName");
				levelName = jsonResult.optString("levelName");
				memberScore = jsonResult.optString("memberScore");
				memberBalance = jsonResult.optString("memberBalance");
				memberPayToken = jsonResult.optString("memberPayToken");
				text_member_name.setText(memberName);
				text_member_level.setText(levelName);
				text_member_credits.setText(memberScore);
				text_member_amount.setText(memberBalance);

			}

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image_delete:
			edit_code.setText("");
			break;
		// case R.id.text_search:
		// goodsCode = edit_code.getText().toString();
		// if (TextUtils.isEmpty(goodsCode)) {
		// showShortToast("请输入商品码");
		// } else {
		// InputMethodManager imm = (InputMethodManager)
		// mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		// imm.hideSoftInputFromWindow(edit_code.getWindowToken(), 0);
		// netRequest.startRequest(RequestUrls.hostUrl +
		// RequestUrls.posQueryGoodsByCode, Method.POST,
		// NetParams.posQueryGoodsByCode(mContext, goodsCode), 0, listener);
		// }
		// break;
		case R.id.button_clear:
			goodsList.clear();
			adapter.notifyDataSetChanged();
			relative_submit.setVisibility(View.GONE);
			memberCode = "";
			memberPayToken = "";
			memberName = "";
			levelName = "";
			memberScore = "";
			memberBalance = "";
			memberPayToken = "";
			edit_code.setText("");
			edit_member.setText("");
			text_member_amount.setText("");
			text_member_credits.setText("");
			text_member_level.setText("");
			text_member_name.setText("");
			text_member_hint.setVisibility(View.GONE);
			showShortToast("清空成功");
			break;
		case R.id.button_hang:
			if (goodsList.size() == 0) {
				showShortToast("暂无商品");
			} else {
				memberCode = "";
				memberPayToken = "";
				memberName = "";
				levelName = "";
				memberScore = "";
				memberBalance = "";
				memberPayToken = "";
				edit_code.setText("");
				edit_member.setText("");
				text_member_amount.setText("");
				text_member_credits.setText("");
				text_member_level.setText("");
				text_member_name.setText("");
				text_member_hint.setVisibility(View.GONE);
				ContentValues values = new ContentValues();
				values.put(GoodsConstants.NAME, userBean.getUserName());
				values.put(GoodsConstants.DATE, System.currentTimeMillis());
				values.put(GoodsConstants.GOODS, gson.toJson(goodsList, new TypeToken<List<GoodsBean>>() {
				}.getType()));
				Log.e(Tag, "插入 goods=" + gson.toJson(goodsList, new TypeToken<List<GoodsBean>>() {
				}.getType()));
				mContentResolver.insert(HangGoodsProvider.CONTENT_URI, values);
				showShortToast("挂单成功");
			}

			break;

		case R.id.button_input:
			if (linear_input.getVisibility() == View.VISIBLE) {
				linear_input.setVisibility(View.GONE);
			} else {
				linear_input.setVisibility(View.VISIBLE);
			}

			break;
		case R.id.button_member:
			text_member_hint.setVisibility(View.GONE);
			memberDialog.show();
			break;
		case R.id.text_member_search:
			memberCode = edit_member.getText().toString().trim();
			if (TextUtils.isEmpty(memberCode)) {
				text_member_hint.setText("请输入会员号");
				text_member_hint.setVisibility(View.VISIBLE);
				return;
			}
			InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(edit_member.getWindowToken(), 0);
			netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posQueryMember, Method.POST,
					NetParams.posQueryMember(mContext, memberCode), 2, listener);
			break;
		case R.id.button_member_confirm:
			memberDialog.dismiss();
			break;
		case R.id.button_member_clear:
			memberCode = "";
			memberPayToken = "";
			memberName = "";
			levelName = "";
			memberScore = "";
			memberBalance = "";
			memberPayToken = "";
			edit_code.setText("");
			edit_member.setText("");
			text_member_amount.setText("");
			text_member_credits.setText("");
			text_member_level.setText("");
			text_member_name.setText("");
			text_member_hint.setVisibility(View.GONE);
			break;
		case R.id.text_submit:
			// goodsCode|goodsCount, goodsCode|goodsCount
			String goodsCodes = "";
			for (GoodsBean item : goodsList) {
				goodsCodes = goodsCodes + "," + item.getCode() + "|" + item.getNum();
			}
			Map map=new HashMap();
			goodsCodes = goodsCodes.substring(1, goodsCodes.length());
			netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posCreateOrder, Method.POST,
					NetParams.posCreateOrder(mContext, goodsCodes, memberPayToken), 1, listener);

			break;

		default:
			break;
		}

	}

	@Override
	public void onBackPressed() {
		commonDialog.showDialog("确定退出收银台？", "确定", new OnClickListener() {

			@Override
			public void onClick(View v) {
				commonDialog.dismissDialog();
				finish();

			}
		});
	}

}
